﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.RM;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.RiskManager
{
    /// <summary>
    /// Логика взаимодействия для newRMItem.xaml
    /// </summary>
    public partial class NewRmItem : Window
    {
        private RmItem rmItem;
        private DataClass.Data data;
        List<Trade> trades;

        public NewRmItem ( RmItem rmItem, DataClass.Data data, bool isedit )
        {
            InitializeComponent( );
            this.rmItem = rmItem;
            this.data = data;

            trades = data.GetTradeList( );
            
            var result = new List<Trade>( );

            for ( int j = 0; j < trades.Count; j++ )
            {
                bool tr = false;

                for ( int i = 0; i < data.RMItems.Count; i++ )
                {
                    if ( trades [ j ].Account == data.RMItems [ i ].Account && trades [ j ].ClientCode == data.RMItems [ i ].ClientCode )
                    {
                           tr = true;
                    }
                }

                if ( tr == false )
                    result.Add( trades [ j ] );
            }
            trades = result;
            if ( isedit == true )
                trades.Add( new Trade( ) { Account = rmItem.Account, ClientCode = rmItem.ClientCode } );
            
            // загрузка данных
            ComboBox_ClientCode.ItemsSource = trades.Select( a => a.ClientCode ).ToList( );
            CmbxTypeCalculation.ItemsSource = new List<string>() { cfg.Unknown, cfg.Persent, cfg.Rub }; ;
            ComboBox_TypeEnterLimit.ItemsSource = new List<string>() { cfg.Unknown,cfg.TypeEnterLimitRmCalcRmBasic, cfg.TypeEnterLimitRmTrallingProfit, cfg.TypeEnterLimitRmDealTrallingProfit };
            ComboBox_Modes.ItemsSource = new List<string>() { cfg.Unknown, cfg.Mode0, cfg.Mode1, cfg.Mode2 };

            //checkBox1.IsChecked = rmItem.kGO == 2 ? true : false;

            //if ( rmItem.Stage == 0 )
            //    rmItem.Stage = 1;

           
            if ( rmItem.DrowDown == 0 )
                rmItem.DrowDown = 1;

            //TextBox_Stages.Text = rmItem.Stage.ToString( );
            //TextBox_Unblocking.Text = rmItem.Unblock.ToString( );
            TextBox_DrawDown.Text = rmItem.DrowDown.ToString( );
            //TextBoxComisBlock.Text = rmItem.ComisBlock.ToString( );
            //CheckBoxComisBlock.IsChecked = rmItem.RunComicBlock;
            //CheckBox_Consider_VM_ND.IsChecked = rmItem.ConsiderVMND;
            txbxProfit.Text = rmItem.ProfitBlock.ToString();

            if (!rmItem.UseDefensePofit)
            {
                TxbxDegreseProfit.IsEnabled = false;
                TxbxPlanProfit.IsEnabled = false;
                LblPlanProfit.Foreground = Brushes.Gray;
                LblDefreseProfit.Foreground = Brushes.Gray;
            }
            TxbxPlanProfit.Text = rmItem.PlanProfit.ToString();
            TxbxDegreseProfit.Text = rmItem.DecreaseProfit.ToString();
            
            ChbxUseDefenseProfit.IsChecked = rmItem.UseDefensePofit;

            int index = 0;
            foreach ( var tmp in trades )
            {
                if ( tmp.ClientCode == rmItem.ClientCode )
                {
                    if ( tmp.Account == tmp.ClientCode)
                    {
                        ComboBox_Modes.IsEnabled = true;
                        ComboBox_Modes.SelectedIndex = 0;
                    }
                    else
                    {
                        ComboBox_Modes.IsEnabled = false;
                        ComboBox_Modes.SelectedIndex = 3;
                    }

                    ComboBox_ClientCode.SelectedIndex = index;
                }

                index++;
            }
            
            for ( int i = 0; i < ComboBox_Modes.Items.Count; i++ )
            {
                if ( ComboBox_Modes.Items [ i ].ToString( ) == rmItem.Variable )
                    ComboBox_Modes.SelectedIndex = i;
            }

            for ( int i = 0; i < CmbxTypeCalculation.Items.Count; i++ )
            {
                if ( CmbxTypeCalculation.Items [ i ].ToString() == rmItem.TypeCalcutation )
                    CmbxTypeCalculation.SelectedIndex = i;
            }
            
            for ( int i = 0; i < ComboBox_TypeEnterLimit.Items.Count; i++ )
            {
                if ( ComboBox_TypeEnterLimit.Items [ i ].ToString( ) == rmItem.TypeEnterLimite )
                    ComboBox_TypeEnterLimit.SelectedIndex = i;
            }
        }

      
        private void Button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Button_Accept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //rmItem.ConsiderVMND = CheckBox_Consider_VM_ND.IsChecked.Value;
                //rmItem.RunComicBlock = CheckBoxComisBlock.IsChecked.Value;
                //rmItem.ComisBlock = Convert.ToDouble( TextBoxComisBlock.Text );
                rmItem.ProfitBlock = Convert.ToDouble(txbxProfit.Text);
                //rmItem.TimeStrartreductionGOEvening = (new TimeSpan(Convert.ToInt32((txbxTimeEveningStrartGO.Text.Split(':'))[0]), Convert.ToInt32((txbxTimeEveningStrartGO.Text.Split(':'))[1]),
                //   Convert.ToInt32((txbxTimeEveningStrartGO.Text.Split(':'))[2]))).TotalSeconds;

                if (ComboBox_ClientCode.SelectedIndex >= 0)
                {
                    rmItem.ClientCode = ComboBox_ClientCode.SelectedValue.ToString( );
                    List<Trade> trades = data.GetTradeList( );

                    for ( int i = 0; i < trades.Count; i++ )
                        if ( trades [ i ].ClientCode == rmItem.ClientCode )
                            rmItem.Account = trades [ i ].Account;
                }
                else
                {
                    new DialogOkCancel( "Выберите код клиента(счет)!", "Ошибка добавления" );
                    return;
                }

                if ( CmbxTypeCalculation.SelectedIndex > 0 )
                    rmItem.TypeCalcutation = CmbxTypeCalculation.SelectedValue.ToString( );
                else
                {
                    new DialogOkCancel( "Выберите тип расчета!", "Ошибка добавления" );
                    return;
                }

                if ( ComboBox_TypeEnterLimit.SelectedIndex > 0 )
                    rmItem.TypeEnterLimite = ComboBox_TypeEnterLimit.SelectedValue.ToString( );
                else
                {
                    new DialogOkCancel( "Выберите тип расчета лимита!", "Ошибка добавления" );
                    return;
                }

                if ( ComboBox_Modes.SelectedIndex > 0 )
                    rmItem.Variable = ComboBox_Modes.SelectedValue.ToString( );
                else
                {
                    new DialogOkCancel( "Выберите вариант расчета убытков!", "Ошибка добавления" );
                    return;
                }

                if ( TextBox_DrawDown.Text.Trim( ).Length != 0 )
                    rmItem.DrowDown = cfg.ToDoubleFormControls( TextBox_DrawDown.Text );
                else
                    rmItem.DrowDown = 10;
                rmItem.UseDefensePofit = Convert.ToBoolean(ChbxUseDefenseProfit.IsChecked);
                

                rmItem.PlanProfit = Convert.ToDouble(TxbxPlanProfit.Text);
                rmItem.DecreaseProfit = Convert.ToDouble( TxbxDegreseProfit.Text);
                if (rmItem.UseDefensePofit && rmItem.PlanProfit <= 0)
                {
                    new DialogOkCancel("Активирован режми защиты прибыли. Необходимо, чтоб планируемая прибыль была больше нуля", "Ошибка добавления");
                    return;
                }

                this.Close();
            }
            catch (Exception)
            {
            }
        }

        private void TextBox_DrawDown_TextChanged ( object sender, TextChangedEventArgs e )
        {

        }

        private void Window_Loaded ( object sender, RoutedEventArgs e )
        {

        }

        private void ComboBox_ClientCode_SelectionChanged ( object sender, SelectionChangedEventArgs e )
        {
            for ( int i = 0; i < trades.Count; i++ )
            {
                if ( ComboBox_ClientCode.SelectedIndex >= 0 )
                {
                    if ( trades [ i ].ClientCode == ComboBox_ClientCode.SelectedItem.ToString( ) )
                    {
                        if ( trades [ i ].Account == trades[i].ClientCode )
                        {
                            ComboBox_Modes.IsEnabled = true;
                            ComboBox_Modes.SelectedIndex = 0;
                        }
                        else
                        {
                            ComboBox_Modes.IsEnabled = false;
                            ComboBox_Modes.SelectedIndex = 3;
                            ComboBox_ClientCode.SelectedIndex = i;
                        }
                    }
                }
            }
        }

        private void ComboBox_Modes_SelectionChanged ( object sender, SelectionChangedEventArgs e )
        {
            if ( ComboBox_Modes.SelectedIndex == 3 )
            {
                ComboBox_ClientCode.SelectedIndex = -1;
            }
        }

        //private void TextBoxComisBlock_TextChanged ( object sender, TextChangedEventArgs e )
        //{
        //    string result = "";
        //    for ( int i = 0; i < ( sender as TextBox ).Text.Length; i++ )
        //    {
        //        if ( ( sender as TextBox ).Text [ i ] == '.' )
        //            result += ',';
        //        else
        //            result += ( sender as TextBox ).Text [ i ];
        //    }
        //    TextBoxComisBlock.Text = result;
        //    TextBoxComisBlock.Select( TextBoxComisBlock.Text.Length, 0 );
        //    //TextBoxComisBlock.ScrollToCaret( );
        //}

        private void checkBox1_Checked(object sender, RoutedEventArgs e)
        {
            //txbxReductionGO.IsEnabled = Convert.ToBoolean(checkBox1.IsChecked);
        }

        private void ChbxUseDefenseProfit_Checked(object sender, RoutedEventArgs e)
        {
            TxbxDegreseProfit.IsEnabled = Convert.ToBoolean (((CheckBox)sender).IsChecked);
            TxbxPlanProfit.IsEnabled = Convert.ToBoolean(((CheckBox)sender).IsChecked);
            LblPlanProfit.Foreground = Brushes.White;
            LblDefreseProfit.Foreground = Brushes.White;
        }

        private void ChbxUseDefenseProfit_Unchecked(object sender, RoutedEventArgs e)
        {
            TxbxDegreseProfit.IsEnabled = Convert.ToBoolean(((CheckBox)sender).IsChecked);
            TxbxPlanProfit.IsEnabled = Convert.ToBoolean(((CheckBox)sender).IsChecked);
            LblPlanProfit.Foreground = Brushes.Gray;
            LblDefreseProfit.Foreground = Brushes.Gray;
        }

    }
}
